package cn.com.bluemoon.daps.common.toolkit;

import cn.com.bluemoon.daps.common.domain.ResultBean;
import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import feign.FeignException;

/**
 * @author Jarod.Kong
 * @date 2021/1/19 13:15
 */
public enum FeignClientTools {
    INSTANCE;
    public static final String FEIGN_FLAG = "; content:\\n";

    /**
     * feign.FeignException#errorStatus(java.lang.String, feign.Response)
     * 针对feignException捕获到的异常处理结构进行解析，拿到上游异常信息（依赖feign-core-9.5.1.jar，不确定版本差异导致打印的信息是否一致）
     * feign message:
     * <code>
     * status 403 reading RemoteStandardBasicService#getBasic(String); content:
     * {"code":403,"msg":"认证无效，禁止访问：服务注册-基础标准服务","content":null,"moreData":null,"cost":null,"pageContent":false}
     * </code>
     * 目前识别标记为："; content:\n"
     *
     * @param e feign
     * @return 解析结果
     */
    public <T> ResultBean<T> errorMsgCatch(Throwable e, final String serviceName, String errorMsg) {
        if (e != null) {
            if (e instanceof FeignException) {
                FeignException fe = (FeignException) e;
                if (fe.status() == ResultBean.FORBIDDEN.getCode()) {
                    String message = fe.getMessage();
                    String[] split = new String[0];
                    if (message != null && (split = message.split(FEIGN_FLAG)).length > 0) {
                        String respContent = split[1];
                        try {
                            @SuppressWarnings("unchecked")
                            ResultBean<T> resultBean = JSON.parseObject(respContent, ResultBean.class);
                            return resultBean;
                        } catch (Exception inE) {
                            inE.printStackTrace();
                            return ResultBean.<T>error(inE.getMessage()).setCode(ResultBean.FORBIDDEN.getCode());
                        }
                    }
                    return ResultBean.<T>error(fe.getMessage());
                } else if (fe.status() == ResultBean.UNAUTHORIZED.getCode()) {
                    // 无权访问
                    return ResultBean.<T>error(fe.getMessage()).setCode(ResultBean.UNAUTHORIZED.getCode());
                }
            } else if (e instanceof HystrixTimeoutException) {
                HystrixTimeoutException hte = (HystrixTimeoutException) e;
                if (hte.getMessage() != null) {
                    return ResultBean.<T>error(hte.getMessage());
                } else {
                    return ResultBean.error("请求服务[" + serviceName + "]超时异常");
                }
            }
        }
        return ResultBean.error(errorMsg);
    }

}
